import React from "react";
import { connect } from "react-redux";
import menuRoute from "routes/menuRoute";
import { Tag, Input, Popover } from "antd";
import SearchArea from "components/search-area";
const Search = Input.Search;
import constants from "share/constants";
import expenseReportService from "containers/expense-report/expense-report.service";
import debounce from "lodash.debounce";
import moment from "moment";
import "styles/request/request.scss";
import Stations from "components/template/proxies/stations";
import Proxies from "components/template/proxies/proxies";
import {
  dealCache,
  messages,
  queryCurrencyPrecision,
  dealListTag,
} from "share/common";
import { setExpenseReport } from "actions/cache";
import configureStore from "stores";
import ResizeTable from "components/resize-table";
import baseService from "share/base.service";
import errorMessage from "share/errorMessage";

let cacheSearchData = {};

class ExpenseReport extends React.Component {
  constructor(props) {
    super(props);
    constants.documentStatus.map((status) => (status.label = status.text));
    this.state = {
      loading: false,
      checkboxListForm: [
        {
          id: "status",
          single: true,
          items: [
            {
              label: messages("common.column.status"),
              key: "statusWithReject",
              checked: ["1001100210031004100510061007100810101015"],
              options: [
                {
                  label: messages("expense-parent-report.key57" /*全部*/),
                  value: "1001100210031004100510061007100810101015",
                  operate: "",
                },
                //fix bug25401 【取消支付】搜索条件需要读取租户级profile
                ...constants.expenseStatus.filter((item) =>
                  props.profile["finance.payment.cancel"]
                    ? true
                    : item.value !== "1015"
                ),
              ],
            },
          ],
        },
        {
          id: "formOID",
          single: true,
          items: [
            {
              label: messages("common.document.name"),
              key: "formOID",
              options: [{ label: messages("common.all"), value: "all" }],
              checked: ["all"],
            },
          ],
        },
      ],
      searchForm: [
        {
          type: "items",
          id: "dateRange",
          items: [
            {
              type: "date",
              id: "startDate",
              label: messages("expense-parent-report.key210") /*提交日期从*/,
              event: "DATE",
            },
            {
              type: "date",
              id: "endDate",
              label: messages("expense-parent-report.key211") /*提交日期至*/,
              event: "DATE",
            },
          ],
        },
        {
          type: "radio",
          label: messages("common.date.range"),
          id: "dateOption",
          event: "DATE_RANGE",
          defaultValue: 0,
          options: [
            { label: messages("common.all"), value: 0 },
            { label: messages("common.this.month"), value: 1 },
            { label: messages("common.last.three.month"), value: 3 },
          ],
        },
        {
          type: "list",
          id: "applicantOIDs",
          label: messages("approve.key64" /*申请人*/),
          listType: "user_condition",
          labelKey: "fullName",
          valueKey: "userOID",
          listExtraParams: {
            roleType: "TENANT",
            setOfBooksId: props.company.setOfBooksId,
          },
        },
      ],
      searchParams: { status: "1001100210031004100510061007100810101015" },
      columns: [
        {
          title: messages("common.sequence"),
          dataIndex: "index",
          render: (value, record, index) =>
            index + 1 + this.state.pageSize * this.state.page,
          width: 48,
        },
        {
          title: messages("common.submit.date"),
          dataIndex: "submittedDate",
          render: (value, record) =>
            moment(record.lastSubmittedDate || record.createdDate).format(
              "YYYY-MM-DD"
            ),
          width: 120,
        },
        {
          title: messages("common.applicant"),
          dataIndex: "applicantName",
          width: "8%",
          render: (value) => <Popover content={value}>{value}</Popover>,
        },
        {
          title: messages("common.document.name"),
          dataIndex: "formName",
          render: (value) =>
            value ? (
              <Popover
                placement="topLeft"
                content={value}
                overlayStyle={{ maxWidth: 500 }}
              >
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.subjectmatter"),
          dataIndex: "title",
          render: (value) =>
            value ? (
              <Popover
                placement="topLeft"
                content={value}
                overlayStyle={{ maxWidth: 500 }}
              >
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.document.code"),
          dataIndex: "businessCode",
          render: (value) =>
            value ? (
              <Popover
                placement="topLeft"
                content={value}
                overlayStyle={{ maxWidth: 500 }}
              >
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.currency"),
          dataIndex: "currencyCode",
          width: 48,
        },
        {
          title: messages("common.amount"),
          dataIndex: "totalAmount",
          align: "right",
          render: (value, item) =>
            this.filterMoney(value, queryCurrencyPrecision(item.currencyCode)),
          width: "7%",
        },
        {
          title: messages("expense-parent-report.key237") /*本币币种*/,
          dataIndex: "baseCurrencyCode",
          width: 76,
        },
        {
          title: messages("expense-parent-report.key238") /*本币金额*/,
          dataIndex: "baseTotalAmount",
          align: "right",
          render: (value, item) =>
            this.filterMoney(value, queryCurrencyPrecision(item.currencyCode)),
          width: "7%",
        },
        {
          title: messages("common.column.status"),
          dataIndex: "status",
          width: props.language.code === "zh_cn" ? "10%" : "13%",
          render: (value, record) => {
            return this.state.checkboxListForm.map((form) => {
              if (form.id === "status") {
                return constants.documentStatus.map((item) => {
                  if (
                    (item.value === String(value) &&
                      record.rejectType === 1000) ||
                    item.value === String(value * 10000 + record.rejectType)
                  ) {
                    return <Tag color={item.color}>{item.label}</Tag>;
                  }
                });
              }
            });
          },
        },
        // {
        //   title: messages("common.operation") /*操作*/,
        //   width: "7%",
        //   dataIndex: "printView",
        //   render: (value, record) =>
        //     value === 1 ? (
        //       <a onClick={(e) => this.handlePrint(e, record)}>
        //         {messages("common.print") /*打印*/}
        //       </a>
        //     ) : null,
        // },
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100", "200"],
      },
      expenseReportDetail: menuRoute.getRouteItem("expense-report-detail"),
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount() {
    this.getForms();
  }

  componentDidUpdate(prevProps) {
    const path = this.props.route.path;
    const prevPath = prevProps.route.path;
    if (path !== prevPath) {
      this.getForms()
    }
  }


  /**
   * 根据当前url判断当前是哪种报销单
   * @returns {{ type: number, key: string}} expenseReportType
   */
  getApplicationFormDetail() {
    const path = this.props.route.path;
    let keys = [
      {key: "expense-report", type: 7, path: "/main/expense-parent-report/expense-report" },
      {key: "union-expense-report", type: 8,  },
    ]
    return keys.find(item => {
      let match = true
      if (path.indexOf(item.key) === -1) {
        match = false
      }
      if (item.path) {
        if (!path.startsWith(item.path)) {
          match = false
        }
      }
      return match
    })
  }


  //存储筛选数据缓存
  setCache(result) {
    let { page } = this.state;
    result.page = page;
    cacheSearchData = result;
  }
  //获取筛选数据缓存
  getCache() {
    let result = this.props.expenseReport;
    if (result && JSON.stringify(result) !== "{}") {
      let { checkboxListForm } = this.state;
      checkboxListForm.map((item, index) => {
        checkboxListForm[index].items[0].checked = [result[item.id]] || [];
      });
      cacheSearchData = result;
      this.setState({ checkboxListForm }, () => {
        this.dealCache(result);
      });
    } else {
      this.getList();
    }
  }
  //处理筛选缓存数据
  dealCache(result) {
    let { searchForm, page } = this.state;
    if (result) {
      page = result.page;
      dealCache(searchForm, result);
      this.setState({ searchForm, page }, () => {
        this.search(result);
        configureStore.store.dispatch(setExpenseReport(null));
      });
    }
  }
  searchEventHandle = (event, value) => {
    if (event === "DATE_RANGE") {
      let startDate, endDate;
      endDate = new Date();
      switch (value) {
        case 0:
          startDate = endDate = null;
          break;
        case 1:
          startDate = new Date().setDate(1);
          break;
        case 3:
          startDate = new Date().calcMonth(-3);
          break;
      }
      this.formRef.setValues({
        startDate: startDate ? moment(startDate) : null,
        endDate: endDate ? moment(endDate) : null,
      });
    } else if (event === "DATE") {
      this.formRef.setValues({
        dateOption: null,
      });
    }
  };

  //获取单据列表
  getForms = () => {
    let { checkboxListForm } = this.state;
    //formType：101（申请单）、102（报销单）、103（全部）
    this.setState({ loading: true });
    const result = this.getApplicationFormDetail()
    const applicationFormType = result.type
    expenseReportService.getDocumentType(102, true, applicationFormType).then((res) => {
      let options = [{ label: messages("common.all"), value: "all" }];
      res.data.map((item) => {
        options.push({ label: item.formName, value: item.formOID });
      });
      checkboxListForm.map((form) => {
        if (form.id === "formOID") {
          form.items.map((item) => {
            item.key === "formOID" && (item.options = options);
          });
        }
      });
      this.setState({ checkboxListForm }, () => {
        this.getCache();
      });
    });
  };

  getList = () => {
    // https://pmo.mcd.com.cn/jira/browse/TES-930
    // 搜索优化，防止新搜索结果被旧搜索结果覆盖
    if (this.abortLatestGetList) this.abortLatestGetList();
    let aborted = false;
    this.abortLatestGetList = () => {
      aborted = true;
    };
    let { page, pageSize, searchParams, pagination, expenseReportType } = this.state;
    this.setState({ loading: true });
    expenseReportService
      .getExpenseReportList(page, pageSize, {
        ...searchParams, 
        expenseReportType, 
        applicationFormType: this.getApplicationFormDetail().type
      })
      .then((res) => {
        if (aborted) {
          return;
        }
        pagination.total = Number(res.headers["x-total-count"]) || 0;
        pagination.current = page + 1;
        pagination.onChange = this.onChangePaper;
        pagination.onShowSizeChange = this.onShowSizeChange;
        let arr = [];
        res.data && res.data.map(item => {
          if (item.warningList) {
            let list = JSON.parse(item.warningList);
            if (list && list.length === 1 && list[0].externalPropertyName === 'CREDIT_SPOT_CHECK') {
              item.warningList = undefined;
            }
          }
        })
        console.log("res.data", res.data)
        this.setState({
          loading: false,
          data: res.data,
          pagination,
        });
      });
  };

  onChangePaper = (page, pageSize) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1, pageSize }, () => {
        this.setCache(cacheSearchData);
        this.getList();
      });
    }
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState({ page: current - 1, pageSize }, () => {
      this.setCache(cacheSearchData);
      this.getList();
    });
  };

  search = (values) => {
    this.setCache({ ...values });
    values.formOID === "all" && (values.formOID = "");
    values.startDate &&
      (values.startDate = moment(values.startDate).format(
        "YYYY-MM-DD+00:00:00"
      ));
    values.endDate &&
      (values.endDate = moment(values.endDate).format("YYYY-MM-DD+23:59:59"));
    this.setState({ searchParams: values, page: 0 }, () => {
      this.getList();
    });
  };

  handleSearch = (value) => {
    this.setCache({ ...value });
    let { searchParams, pagination } = this.state;
    searchParams.businessCode = value;
    pagination.current = 1;
    this.setState(
      {
        page: 0,
        businessCode: value,
        pagination,
        searchParams,
      },
      () => {
        this.getList();
      }
    );
  };
  clear = () => {
    let { pagination } = this.state;
    pagination.total = 0;
    this.setState(
      {
        searchParams: { status: "100110021003100410051006100710081015" },
        page: 0,
        pagination,
      },
      () => {
        this.setCache({});
        this.getList();
      }
    );
  };
  handleRowClick = (record) => {
    configureStore.store.dispatch(setExpenseReport(cacheSearchData));
    // menuRoute.goForm(this, record.formCode, {
    //   action: 'detail',
    //   params: {
    //     expenseReportOID: record.expenseReportOID,
    //     pageFrom: 'my'
    //   }
    // })
    this.context.router.push(
      this.getUrl('detail')
        .replace(":expenseReportOID", record.expenseReportOID)
        .replace(":pageFrom", "my")
    );
  };

  getUrl = (urlType) => {
    const { key } = this.getApplicationFormDetail()
    let url = ''
    if(urlType === 'detail') {
      url = menuRoute.getRouteItem(`${key}-detail`).url
    } else if (urlType === 'new') {
      url = menuRoute.getRouteItem(`new-${key}`).url
    }

    url += `?backUrlKey=${key}`
    return url
  }

  //新建报销单
  handleNewExpenseReport = (
    formOid,
    jobId,
    userOID,
    ifProxy = false,
    driverId = null,
    driverVerdor = null
  ) => {
    let url = this.getUrl('new')
    const proxy = ifProxy ? 1 : 0;
    if (driverId) {
      expenseReportService.checkProxyRelIsOverDate({ vendor: driverVerdor, employeeID: this.props.user.employeeID }).then(res => {
        // console.log(res)
        if (res.status === 200) {
          this.context.router.push(
            url
              .replace(":formId", formOid)
              .replace(":userOID", userOID)
              .replace(":applicantJobId", jobId)
              .replace(":proxy", proxy)
              .replace(":driverId", driverId)
          );
        }
      }).catch(err => {
        errorMessage(err.response);
      })
    } else {
      this.context.router.push(
        url
          .replace(":formId", formOid)
          .replace(":userOID", userOID)
          .replace(":applicantJobId", jobId)
          .replace(":proxy", proxy)
      );
    }
  };

  handlePrint = (e, info) => {
    e.stopPropagation();
    baseService
      .printExpense(info.expenseReportOID)
      .then((res) => {
        window.open(res.data.link, "_blank");
      })
      .catch((err) => {
        errorMessage(err.response);
      });
  };

  render() {
    const {
      loading,
      checkboxListForm,
      searchForm,
      columns,
      data,
      pagination,
    } = this.state;
    return (
      <div className="application-list">
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          checkboxListForm={checkboxListForm}
          eventHandle={this.searchEventHandle}
          clearHandle={this.clear}
          wrappedComponentRef={(inst) => (this.formRef = inst)}
        />
        <div className="table-header">
          <div className="table-header-title">
            {
              messages("common.total", {
                total: pagination.total,
              }) /*共搜索到 {pagination.total} 条数据*/
            }
          </div>
          <div className="table-header-buttons">
            {/*新建报销单（包含多岗的情况）*/}
            <Stations type={this.getApplicationFormDetail().type} formType="102" onOk={this.handleNewExpenseReport} />

            {/*代理制单*/}
            {<Proxies type={this.getApplicationFormDetail().type} formType="102" onOk={this.handleNewExpenseReport} />}

            <Search
              className="input-search"
              placeholder={messages(
                "expense-parent-report.key59" /*请输入报销单号*/
              )}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </div>
        </div>
        <ResizeTable
          rowKey="expenseReportOID"
          columns={columns}
          expandedRowRender={dealListTag}
          dataSource={data}
          pagination={pagination}
          onRow={(record) => ({ onClick: () => this.handleRowClick(record) })}
          loading={loading}
          rowClassName={(record) =>
            record.printFree || record.warningList
              ? ""
              : "row-expand-display-none"
          }
          bordered
          size="middle"
        />
      </div>
    );
  }
}

ExpenseReport.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    expenseReport: state.cache.expenseReport,
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.loginUser
  };
}

export default connect(mapStateToProps)(ExpenseReport);
